<template>
  <el-dialog v-model="dialogVisible" width="832px" append-to-body>
    <Title :title="dialogTitle" />
    <div class="dialog-container">
      <el-form :model="form" label-width="auto" ref="formRef" :rules="rules">
        <el-form-item label="学院" prop="deptId">
          <el-select size="large" v-model="form.deptId" placeholder="请选择学院" filterable clearable style="width: 100%" @change="onDeptChange">
          <el-option v-for="opt in deptOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
       <el-form-item label="年级" prop="gradeId">
        <el-select size="large" v-model="form.gradeId" placeholder="请选择年级" filterable clearable style="width: 100%" :disabled="!form.deptId">
          <el-option v-for="opt in gradeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="专业名称" prop="majorName">
        <el-input size="large" v-model="form.majorName" placeholder="请输入专业名称" @input="handleInput" />
      </el-form-item>
      <el-form-item label="全称" prop="gradeMajorName">
        <el-input size="large" v-model="form.gradeMajorName" disabled placeholder="请输入全称" />
      </el-form-item>
    </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel" class="defauleButton">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addMajor, updateMajor, getMajor } from '@/api/major'
import { getGradeTree } from '@/api/grade'
import { ref, getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import Title from '@/components/Title/index.vue'
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const emit = defineEmits(['update'])
const form = ref({
  gradeId: '',
  majorName: '',
  gradeMajorName: '',
  groupFlag: '',
  status: '',
  deptId: ''
})
// 学院、年级下拉选项
const deptOptions = ref([])
const gradeOptions = ref([])
const gradeTreeData = ref([])
const rules = ref({
  majorName: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
  gradeId: [{ required: true, message: '请选择年级', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择学院', trigger: 'change' }]
})
const cancel = () => close()

// 专业名称输入时，自动填充全称
const handleInput = () => {
  form.value.gradeMajorName = `${gradeOptions.value.find((opt) => opt.value === form.value.gradeId)?.label}${form.value.majorName}`
}
const confirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const action = form.value.majorId ? updateMajor : addMajor
      action(form.value).then(() => {
        proxy.$modal.msgSuccess('操作成功')
        emit('update')
        close()
      })
    }
  })
}
const close = () => (dialogVisible.value = false)
const reset = () => {
  form.value = {
    gradeId: '',

    majorName: '',

    gradeMajorName: '',

    updateBy: '',

    updateTime: '',
    groupFlag: '',

    remark: '',

    status: '',
    deptId: ''
  }
  proxy.resetForm('formRef')
  // 清空选项
  gradeOptions.value = []
}
const init = (id) => {
  reset()
  dialogTitle.value = id ? '修改专业信息' : '新增专业信息'
  // 加载学院与年级下拉选项
  loadDeptAndGrades()
  id && getDetail(id)
}
const getDetail = (id) => {
  getMajor(id).then((res) => {
    form.value = res.data
    // 保证下拉选择的值类型为字符串
   // 根据已有的 deptId 更新年级下拉
    updateGradeOptions()
  })
}
const openDialog = (id = null) => {
  dialogVisible.value = true
  init(id)
}
defineExpose({ openDialog })

// 联动：当学院改变时，更新年级下拉并清空已选年级
function onDeptChange() {
  form.value.gradeId = ''
  updateGradeOptions()
}

async function loadDeptAndGrades() {
  try {
    const res = await getGradeTree()
    const list = Array.isArray(res.data) ? res.data : []
    gradeTreeData.value = list
    deptOptions.value = list.map((item) => ({ label: item.deptName, value: item.deptId }))
    updateGradeOptions()
  } catch (e) {
    deptOptions.value = []
    gradeOptions.value = []
  }
}

function updateGradeOptions() {
  const deptId = form.value.deptId
  if (!deptId) {
    gradeOptions.value = []
    return
  }
  const deptNode = gradeTreeData.value.find((item) => item.deptId === deptId)
  gradeOptions.value = (deptNode?.children || []).map((g) => ({ label: g.gradeName, value: g.gradeId }))
}
</script>
